package com.sadam.ui4.FragmentSearchPage;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.GestureDetector;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.ImageButton;
import android.widget.Toast;

import android.widget.VideoView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.PagerSnapHelper;
import androidx.recyclerview.widget.RecyclerView;

import com.sadam.ui4.Data.MySqLiteOpenHelper;
import com.sadam.ui4.Data.User;
import com.sadam.ui4.Data.Video;
import com.sadam.ui4.FragmentCommentPage.CommentAdapter;
import com.sadam.ui4.FragmentHomePage.VideoAdapter;
import com.sadam.ui4.MainActivity;
import com.sadam.ui4.MyVideoView;
import com.sadam.ui4.R;
import com.sadam.ui4.Data.Comment;

import java.util.ArrayList;
import java.util.List;
public class FragmentSearchPage extends DialogFragment {

    private EditText etSearch;
    private Button btnSearch;
    private RecyclerView recyclerView;
    private TextView tvEmpty;
    private ImageButton btnClose;
    private VideoAdapter videoAdapter;
    private MySqLiteOpenHelper dbHelper;
    // ✅ 新增：持有 MainActivity 的引用
    private MainActivity mainActivity;
    public FragmentSearchPage() {
        // Required empty public constructor
    }
    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        if (context instanceof MainActivity) {
            mainActivity = (MainActivity) context;
        } else {
            throw new RuntimeException("FragmentSearchPage 必须依附于 MainActivity");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mainActivity = null; // 避免内存泄漏
    }
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStyle(DialogFragment.STYLE_NORMAL, R.style.FullScreenDialogStyle); // 全屏样式
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_search_page, container, false);
        initView(view);
        return view;
    }

    private void initView(View view) {
        etSearch = view.findViewById(R.id.et_search);
        btnSearch = view.findViewById(R.id.btn_search);
        recyclerView = view.findViewById(R.id.recyclerview_search);
        tvEmpty = view.findViewById(R.id.tv_empty);
        btnClose = view.findViewById(R.id.btn_close);

        // 初始化数据库
        dbHelper = new MySqLiteOpenHelper(getContext(),
                MySqLiteOpenHelper.DATABASE_NAME, null,
                MySqLiteOpenHelper.DATABASE_VERSION);

        // 设置适配器
        videoAdapter = new VideoAdapter((MainActivity) getActivity(), dbHelper);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerView.setAdapter(videoAdapter);

        // 使用 PagerSnapHelper 实现“一页一视频”的滑动效果
        PagerSnapHelper pagerSnapHelper = new PagerSnapHelper();
        pagerSnapHelper.attachToRecyclerView(recyclerView);

        // 搜索按钮点击事件
        btnSearch.setOnClickListener(v -> performSearch());

        // 关闭按钮点击事件
        btnClose.setOnClickListener(v -> dismiss());

        // 输入框回车搜索
        etSearch.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                performSearch();
                return true;
            }
            return false;
        });

        // 初始状态显示空提示
        showEmptyState(true, "请输入标签关键词搜索视频");
    }

    /**
     * 执行搜索
     */
    private void performSearch() {
        String keyword = etSearch.getText().toString().trim();

        if (keyword.isEmpty()) {
            Toast.makeText(getContext(), "请输入搜索关键词", Toast.LENGTH_SHORT).show();
            return;
        }

        // 隐藏软键盘
        hideKeyboard();

        // 显示加载状态
        showEmptyState(true, "搜索中...");

        new Thread(() -> {
            try {
                // 搜索视频
                List<Video> searchResults = dbHelper.searchVideosByLabel(keyword);

                if (getActivity() != null) {
                    getActivity().runOnUiThread(() -> {
                        if (searchResults.isEmpty()) {
                            showEmptyState(true, "未找到相关视频");
                        } else {
                            showEmptyState(false, "");
                            videoAdapter.setVideos(searchResults);
                            Toast.makeText(getContext(),
                                    "找到 " + searchResults.size() + " 个相关视频",
                                    Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            } catch (Exception e) {
                Log.e("FragmentSearchPage", "搜索失败: " + e.getMessage(), e);
                if (getActivity() != null) {
                    getActivity().runOnUiThread(() -> {
                        showEmptyState(true, "搜索失败，请重试");
                        Toast.makeText(getContext(), "搜索失败: " + e.getMessage(),
                                Toast.LENGTH_SHORT).show();
                    });
                }
            }
        }).start();
    }

    /**
     * 显示/隐藏空状态
     */
    private void showEmptyState(boolean show, String message) {
        if (show) {
            tvEmpty.setText(message);
            tvEmpty.setVisibility(View.VISIBLE);
            recyclerView.setVisibility(View.GONE);
        } else {
            tvEmpty.setVisibility(View.GONE);
            recyclerView.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 隐藏软键盘
     */
    private void hideKeyboard() {
        InputMethodManager imm = (InputMethodManager) getContext()
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null && getView() != null) {
            imm.hideSoftInputFromWindow(getView().getWindowToken(), 0);
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        // 设置对话框全屏
        Dialog dialog = getDialog();
        if (dialog != null) {
            Window window = dialog.getWindow();
            if (window != null) {
                window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
                window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
            }
        }
    }
    /**
     * 在 DialogFragment 显示时暂停首页视频
     */
    @Override
    public void onResume() {
        super.onResume();
        // ✅ 显示时暂停首页视频
        if (mainActivity != null) {
            mainActivity.pauseHomePageVideos();
        }
    }

    /**
     * 在 DialogFragment 关闭时恢复首页视频
     */
    @Override
    public void dismiss() {
        super.dismiss();
        // ✅ 关闭时恢复首页视频
        if (mainActivity != null) {
            mainActivity.resumeHomePageVideos();
        }
    }
}
